package com.hhhn.wk.main.fragment;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseActivity;
import com.hhhn.wk.base.BaseFragment;
import com.hhhn.wk.main.tab1.SearchActivity;
import com.hhhn.wk.main.tab2.adapter.ClassifyAdaper;
import com.hhhn.wk.main.tab2.adapter.NoScrollViewPager;
import com.hhhn.wk.main.tab2.adapter.OneClass;
import com.hhhn.wk.main.tab2.adapter.TwoClass;
import com.hhhn.wk.main.tab2.entity.Gate;
import com.hhhn.wk.main.tab2.view.CommodityListActivity;
import com.hhhn.wk.main.tab2.view.xiangqing.activity.CommodityXQActivity;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.Constants;
import com.hhhn.wk.widget.banner.Banners;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 */
public class TabFragment02 extends BaseFragment {

    private static String oneImg = "";
    private static String oneName = "";
    private static String onedbid = "";
    private static final String TAG = "ClassifyFragment";
    private TextView toolsTextViews[];
    private TextView line_s[];
    private View views[];
    private LayoutInflater inflaters;
    private ScrollView scrollView;
    private int scrllViewWidth = 0, scrollViewMiddle = 0;
    private NoScrollViewPager shop_pager;
    private int currentItem = 0;
    private ShopAdapter shopAdapter;
    Context context;
    LinearLayout toolsLayout;
    public static ArrayList<OneClass> list = new ArrayList<>();
    public static ArrayList<TwoClass> list2 = new ArrayList<>();
    private static ArrayList<Banners> bannersArrayList = new ArrayList<Banners>();

    private static ClassifyAdaper adapters;//右边的

    private LinearLayout ll_header_content;//搜索

    private int isClick = 0;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    showToolsView();
                    initPager();
                    break;
                case 2:
                    initPager();
                    break;
                case 3:

                    break;
            }
            super.handleMessage(msg);
        }
    };


    public TabFragment02() {
        // Required empty public constructor
    }


    @Override
    protected void initView(View mRootView) {
        context = mActivity;
        ll_header_content = findViewById(R.id.ll_header_content);
        toolsLayout = findViewById(R.id.tools);
        scrollView = findViewById(R.id.tools_scrlllview);
        shop_pager = findViewById(R.id.goods_pager);
        inflaters = LayoutInflater.from(context);
    }

    @Override
    protected void initData() {
        getOneClass();
    }
    @Override
    protected void initClick() {
        //搜索
        ll_header_content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(mActivity,SearchActivity.class);
                startActivity(intent);
            }
        });
//        btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent intent = new Intent(mActivity, CommodityListActivity.class);
//                intent.putExtra("title", "分类标题");
//                startActivity(intent);
//            }
//        });
        shop_pager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        shop_pager.requestDisallowInterceptTouchEvent(true);
                        break;
                    case MotionEvent.ACTION_CANCEL:
                        shop_pager.requestDisallowInterceptTouchEvent(false);
                    default:
                        break;
                }
                return true;
            }
        });
        shop_pager.setOnPageChangeListener(onPageChangeListener);
    }
    @Override
    protected int setLayoutResouceId() {
        return R.layout.fragment_tab_fragment02;
    }
    /**
     * 动态生成显示items中的textview
     */
    private void showToolsView() {
//        toolsList=new String[]{"常用分类","潮流女装","品牌男装","内衣配饰","家用电器","手机数码","电脑办公","个护化妆","母婴频道","食物生鲜","酒水饮料","家居家纺","整车车品","鞋靴箱包","运动户外","图书","玩具乐器","钟表","居家生活","珠宝饰品","音像制品","家具建材","计生情趣","营养保健","奢侈礼品","生活服务","旅游出行"};

//        toolsTextViews=new TextView[toolsList.length];
//        line_s=new TextView[toolsList.length];
//        views=new View[toolsList.length];
        toolsTextViews = new TextView[list.size()];
        line_s = new TextView[list.size()];
        views = new View[list.size()];
        for (int i = 0; i < list.size(); i++) {
            View view2 = inflaters.inflate(R.layout.classity_item_left, null);
            view2.setId(i);
            view2.setOnClickListener(toolsItemListener);
            TextView textView = (TextView) view2.findViewById(R.id.text);
            TextView line_ss = (TextView) view2.findViewById(R.id.line_s);
//            textView.setText(toolsList[i]);
            textView.setText(list.get(i).getMsgtypeName());
            toolsLayout.addView(view2);
            toolsTextViews[i] = textView;
            line_s[i] = line_ss;
            views[i] = view2;
        }
        changeTextColor(0);
        if (bannersArrayList.size() == 0) {
            oneImg = "";
        } else {
            oneImg = bannersArrayList.get(0).getPicUrl();
        }
        oneName = list.get(0).getMsgtypeName();
        onedbid = list.get(0).getId();
        Log.d(TAG, "第一次加载一级名字: " + list.get(0).getMsgtypeName());
    }

    //左侧点击
    private View.OnClickListener toolsItemListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: " + v.getId());

            if (isClick == v.getId()) {
                return;
            }
            isClick = v.getId();

            if (v.getId() == 0) {
                changeTextColor(0);
                if (bannersArrayList.size() == 0) {
                    oneImg = "";
                } else {
                    oneImg = bannersArrayList.get(0).getPicUrl();

                }
                oneName = list.get(0).getMsgtypeName();
                onedbid = list.get(0).getId();
                gettwo(0);//刷新二级分类
                initPager();
                shop_pager.setCurrentItem(0);
                shopAdapter.notifyDataSetChanged();
            } else {
                oneName = list.get(v.getId()).getMsgtypeName();
                onedbid = list.get(v.getId()).getId();
                gettwo(v.getId());//刷新二级分类
                initPager();
                shop_pager.setCurrentItem(v.getId());
                changeTextColor(v.getId());
                shopAdapter.notifyDataSetChanged();
            }


        }
    };

    /**
     * initPager<br/>
     * 初始化ViewPager控件相关内容
     */
    private void initPager() {
        shopAdapter = new ShopAdapter(mActivity.getSupportFragmentManager());
        shop_pager.setAdapter(shopAdapter);
        shopAdapter.notifyDataSetChanged();
    }

    /**
     * OnPageChangeListener<br/>
     * 监听ViewPager选项卡变化事的事件
     */

    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int arg0) {
            if (shop_pager.getCurrentItem() != arg0) {
                shop_pager.setCurrentItem(arg0);
            }

            if (currentItem != arg0) {
                changeTextColor(arg0);//改变字体颜色
                changeTextLocation(arg0);//改变左边的位置
            }
            currentItem = arg0;
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    };


    /**
     * ViewPager 加载选项卡
     *
     * @author Administrator
     */
    private class ShopAdapter extends FragmentPagerAdapter {
        public ShopAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int arg0) {
            Fragment fragment = new Classify_allTypeFragment1();
            Bundle bundle = new Bundle();
//            String str=toolsList[arg0];
//            bundle.putString("typename", list.get(arg0).getMsgtypeName());
//            bundle.putString("typeid", list.get(arg0).getId());

            fragment.setArguments(bundle);
            return fragment;
        }

        @Override
        public int getCount() {
            return list.size();
        }
    }

    /**
     * 改变textView的颜色
     *
     * @param id
     */
    private void changeTextColor(int id) {
        for (int i = 0; i < toolsTextViews.length; i++) {
            if (i != id) {
                line_s[i].setBackgroundResource(R.color.cadetblue);
                toolsTextViews[i].setBackgroundResource(android.R.color.white);
                toolsTextViews[i].setTextColor(getResources().getColor(R.color.colorTitle));
            }
        }
        line_s[id].setBackgroundResource(android.R.color.white);
        toolsTextViews[id].setBackgroundResource(R.color.colorbg);
        toolsTextViews[id].setTextColor(getResources().getColor(R.color.colorAccent));
    }

    /**
     * 改变栏目位置
     *
     * @param clickPosition
     */
    private void changeTextLocation(int clickPosition) {
        int x = (views[clickPosition].getTop() - getScrollViewMiddle() + (getViewheight(views[clickPosition]) / 2));
        scrollView.smoothScrollTo(0, x);
    }

    /**
     * 返回scrollview的中间位置
     *
     * @return
     */
    private int getScrollViewMiddle() {
        if (scrollViewMiddle == 0)
            scrollViewMiddle = getScrollViewheight() / 2;
        return scrollViewMiddle;
    }

    /**
     * 返回ScrollView的宽度
     *
     * @return
     */
    private int getScrollViewheight() {
        if (scrllViewWidth == 0)
            scrllViewWidth = scrollView.getBottom() - scrollView.getTop();
        return scrllViewWidth;
    }

    /**
     * 返回view的宽度
     *
     * @param view
     * @return
     */
    private int getViewheight(View view) {
        return view.getBottom() - view.getTop();
    }


    @SuppressLint("ValidFragment")
/**
 * 分类--全部分类的布局
 */
    public static class Classify_allTypeFragment1 extends Fragment {
        public static final String TAG = "Classify_allTypeFragment1";

//        public ImageView iv_toptype;
        public GridView gridView;
        public String typename;
        public String typeid;
//        public ImageView iv_toptype;
        public BaseActivity activity;
        public Intent intents;
        public String iconUrls = "";
//    public Classify_allTypeFragment1(ArrayList<TwoClass> lists_twoClass) {
//            this.lists_twoClass = lists_twoClass;
//        }
        public Classify_allTypeFragment1() {

        }
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_classify_alltype, container, false);
            intents = getActivity().getIntent();
            gridView = (GridView) view.findViewById(R.id.gridView);
//            iv_toptype = ((ImageView) view.findViewById(R.id.toptype));
//
//            if (bannersArrayList.size() == 0) {
//                iv_toptype.setImageResource(R.mipmap.ic_hand_text);
//            } else {
//                Glide.with(getActivity())
//                        .load(Constants.HTTPIMG + bannersArrayList.get(0).getPicUrl())
//                        .error(R.mipmap.img_class)//图片加载错误显示
//                        .into(iv_toptype);
//            }
            if (adapters != null) {
                adapters.notifyDataSetChanged();
            }
            adapters = new ClassifyAdaper(getActivity(), list2);
            gridView.setAdapter(adapters);
            for (int i = 1; i < list2.size(); i++) {
                Log.d(TAG, "Classify_allTypeFragment1: " + list2.get(i).getMsgtypeName());
                Log.d(TAG, "Classify_allTypeFragment1: " + list2.get(i).getIconUrl());
            }
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,final int arg2, long arg3) {
//                    if (new IsLogin(myContext,myActivity).islogin()){

                    String[] listAllName = new String[list2.size()];
                    for (int i = 0; i < list2.size(); i++) {
                        listAllName[i] = list2.get(i).getMsgtypeName();
                    }
                    //跳转到 二级分类 列表页面
                    Intent intent = new Intent(getActivity(), CommodityListActivity.class);
                    intent.putExtra("title_str", list2.get(arg2).getMsgtypeName());
                    intent.putExtra("categoryTwo", list2.get(arg2).getId());
                    startActivity(intent);
                }
            });
            return view;
        }
    }

    //获取一级分类
    private void getOneClass() {
        RequestParams params = AllPublic.getParamsType( mActivity, "/oneType", false);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("获取一级分类", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {//成功

                        JSONArray data = jsonObject.getJSONArray("data");
                        OneClass oneClass = null;
                        for (int i = 0; i < data.length(); i++) {
                            oneClass = new OneClass();
                            JSONObject object = data.getJSONObject(i);
//                            oneClass.setBelongType(object.has("belongType") ? object.getString("belongType") : "");
//                            oneClass.setCreateDate(object.has("createDate") ? object.getString("createDate") : "");
//                            oneClass.setHigherType(object.has("higherType") ? object.getString("higherType") : "");
//                            oneClass.setIsDelete(object.has("isDelete") ? object.getString("isDelete") : "");
//                            oneClass.setMsgtypeCode(object.has("msgtypeCode") ? object.getString("msgtypeCode") : "");

                            oneClass.setId(object.has("id") ? object.getString("id") : "");
//                            oneClass.setIconUrl(object.has("image") ? object.getString("image") : "");
                            oneClass.setMsgtypeName(object.has("name") ? object.getString("name") : "");
                            list.add(oneClass);
                        }
                        handler.sendEmptyMessage(1);
                        getTwoClass(list.get(0).getId());
//                        getBanner(list.get(0).getId());
                    }
                   else {//网络错误
                        mActivity.toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));

                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("获取一级分类-第二个", ex + "");
                ex.printStackTrace();

            }

            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("获取一级分类-第三个", cex + "");

            }

            @Override
            public void onFinished() {
                Log.d("获取一级分类-第四个", "onFinished");

            }
        });
    }

    //获取二级分类
    private void getTwoClass(String id) {
        list2.clear();
        if (adapters != null) {
            adapters.notifyDataSetChanged();
        }
        if (shopAdapter != null) {
            shopAdapter.notifyDataSetChanged();
        }
//        myActivity.showLoad("正在加载");
        RequestParams params = AllPublic.getParamsType((BaseActivity) mActivity, "/twoType", false);
        params.addParameter("parentId", id);//首页分类和发布时的分类显示,根据发布类型传入"文字"内容
        Log.d("获取二级分类", "parentId: " + id);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("获取二级分类", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {//成功

                        JSONArray data = jsonObject.getJSONArray("data");

                        TwoClass twoClass = null;
                        Gate gate = null;
                        for (int i = 0; i < data.length(); i++) {

                            twoClass = new TwoClass();
                            JSONObject object = data.getJSONObject(i);
//                            twoClass.setBelongType(object.has("belongType") ? object.getString("belongType") : "");
//                            twoClass.setCreateDate(object.has("createDate") ? object.getString("createDate") : "");
//                            twoClass.setHigherType(object.has("higherType") ? object.getString("higherType") : "");
                            twoClass.setId(object.has("id") ? object.getString("id") : "");
                            twoClass.setIconUrl(object.has("image") ? object.getString("image") : "");
                            twoClass.setMsgtypeName(object.has("name") ? object.getString("name") : "");

//                            twoClass.setIsDelete(object.has("isDelete") ? object.getString("isDelete") : "");
//                            twoClass.setMsgtypeCode(object.has("XXFL0112") ? object.getString("XXFL0112") : "");
                            list2.add(twoClass);


                        }

                        handler.sendEmptyMessage(2);
                    } else {//网络错误
                        mActivity.toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("获取二级分类-第二个", ex + "");
                ex.printStackTrace();
//                myActivity.dismissLoad();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("获取二级分类-第三个", cex + "");
//                myActivity.dismissLoad();
            }

            @Override
            public void onFinished() {
                Log.d("获取二级分类-第四个", "onFinished");
//                myActivity.dismissLoad();
            }
        });
    }

    private void gettwo(int arg0) {//根据id刷新二级
        OneClass oneClass = list.get(arg0);
//        ToastUtils.showShortToast(context, oneClass.getMsgtypeName());
//        gates.clear();
        list2.clear();
        if (adapters != null) {
            adapters.notifyDataSetChanged();
        }
        if (shopAdapter != null) {
            shopAdapter.notifyDataSetChanged();
        }
        getTwoClass(oneClass.getId());
//        getBanner(oneClass.getId());


        String id = oneClass.getId();
        String msgtypeName = oneClass.getMsgtypeName();
        Log.d(TAG, "gettwo: " + id);
        Log.d(TAG, "gettwo: " + msgtypeName);
    }


    /**
     * banner分类图
     */
    private void getBanner(String id) {
        bannersArrayList.clear();
//        myActivity.showLoad("正在加载");
        RequestParams params = AllPublic.getParams((BaseActivity) getActivity(), "/app/banner/list", false);
        params.addParameter("category", id);//首页 index  广告页  adpage  其他类别 传类别id
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("banner分类图", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String reason = jsonObject.getString("resp_code");
                    if (reason.equals("000000")) {//成功

                        JSONArray banners = jsonObject.getJSONArray("banners");
                        Banners b;
                        for (int i = 0; i < banners.length(); i++) {
                            b = new Banners();
                            JSONObject object = banners.getJSONObject(i);
                            String picUrl = object.has("picUrl") ? object.getString("picUrl") : "";
                            String id = object.has("id") ? object.getString("id") : "";
                            String sort = object.has("sort") ? object.getString("sort") : "";
                            String status = object.has("status") ? object.getString("status") : "";
                            String title = object.has("title") ? object.getString("title") : "";
                            String webUrl = object.has("webUrl") ? object.getString("webUrl") : "";
                            Log.d(TAG, "banners.length(): " + banners.length());
                            Log.d(TAG, "banners.picUrl(): " + object.getString("picUrl"));
                            b.setPicUrl(picUrl);
                            bannersArrayList.add(b);
                        }
                        handler.sendEmptyMessage(2);
                    } else {
                        Toast.makeText(getActivity(), jsonObject.getString("resp_message"), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("banner分类图-第二个", ex + "");
                ex.printStackTrace();
//                myActivity.dismissLoad();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("banner分类图-第三个", cex + "");
//                myActivity.dismissLoad();
            }

            @Override
            public void onFinished() {
                Log.d("banner分类图-第四个", "onFinished");
//                myActivity.dismissLoad();
            }
        });
    }

}
